package com.ctrw.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ctrw.dto.Result;
import com.ctrw.entity.ShopType;
import com.ctrw.mapper.ShopTypeMapper;
import com.ctrw.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result typeList() {
        //1、redis中查询类型
        String type = stringRedisTemplate.opsForValue().get("shopType");
        //2、存在则直接返回
        if (StrUtil.isNotBlank(type)) {
            List<ShopType> list = JSONUtil.toList(type, ShopType.class);
            return Result.ok(list);
        }
        //3、不存在则查询数据库
        List<ShopType> typelist = query().orderByAsc("sort").list();
        //4、数据库不存在则返回null
        if (typelist == null) {
            return Result.fail("店铺不存在");
        }
        //5、更新数据到缓存
        stringRedisTemplate.opsForValue().set("shopType", JSONUtil.toJsonStr(typelist));
        //返回数据
        return Result.ok(typelist);
    }
}
